package com.qf.controller;

import com.qf.pojo.TenderInformation;
import com.qf.service.ContactExtractionService;
import com.qf.service.TenderInformationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/tender")
public class ContactExtractionController {
    private final ContactExtractionService extractionService;

    public ContactExtractionController(ContactExtractionService extractionService) {
        this.extractionService = extractionService;
    }

    /**
     * 提取联系人信息
     *
     * @param request 包含HTML内容的请求体
     * @return 提取结果
     */
    @PostMapping("/extract")
    public ResponseEntity<Map<String, Object>> extractContact(
            @RequestBody Map<String, String> request) {

        String htmlContent = request.get("htmlContent");
        if (htmlContent == null || htmlContent.trim().isEmpty()) {
            return badRequest("htmlContent参数不能为空");
        }

        return extractionService.extractContact(htmlContent)
                .map(contact -> successResponse("contact", contact))
                .orElseGet(() -> successResponse(false, "message", "未找到匹配的联系人信息"));
    }

    /**
     * 添加自定义匹配规则
     *
     * @param request 包含正则表达式的请求体
     * @return 操作结果
     */
    @PostMapping("/patterns")
    public ResponseEntity<Map<String, Object>> addPattern(
            @RequestBody Map<String, String> request) {

        String pattern = request.get("pattern");
        if (pattern == null || pattern.trim().isEmpty()) {
            return badRequest("pattern参数不能为空");
        }

        try {
            extractionService.addCustomPattern(pattern);
            return successResponse(
                    "message", "模式添加成功",
                    "pattern", pattern
            );
        } catch (Exception e) {
            return badRequest("无效的正则表达式: " + e.getMessage());
        }
    }

    /**
     * 获取当前所有匹配规则
     */
    @GetMapping("/patterns")
    public ResponseEntity<Map<String, Object>> getPatterns() {
        return successResponse("patterns", extractionService.getPatterns());
    }

    /**
     * 重置为默认匹配规则
     */
    @PostMapping("/patterns/reset")
    public ResponseEntity<Map<String, Object>> resetPatterns() {
        extractionService.resetToDefaultPatterns();
        return successResponse(
                "message", "已重置为默认匹配规则",
                "patterns", extractionService.getPatterns()
        );
    }

    // 响应构建辅助方法
    private ResponseEntity<Map<String, Object>> successResponse(String key, Object value) {
        return ResponseEntity.ok(createResponse(true, key, value));
    }

    private ResponseEntity<Map<String, Object>> successResponse(boolean success, String key, Object value) {
        return ResponseEntity.ok(createResponse(success, key, value));
    }

    private ResponseEntity<Map<String, Object>> successResponse(Object... keyValuePairs) {
        Map<String, Object> data = new HashMap<>();
        for (int i = 0; i < keyValuePairs.length; i += 2) {
            data.put((String) keyValuePairs[i], keyValuePairs[i + 1]);
        }
        return ResponseEntity.ok(createResponse(true, data));
    }

    private ResponseEntity<Map<String, Object>> badRequest(String message) {
        return ResponseEntity.badRequest().body(createResponse(false, "message", message));
    }

    private Map<String, Object> createResponse(boolean success, String key, Object value) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", success);
        response.put(key, value);
        return response;
    }

    private Map<String, Object> createResponse(boolean success, Map<String, Object> data) {
        Map<String, Object> response = new HashMap<>(data);
        response.put("success", success);
        return response;
    }
}
